{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Room scheduling\n",
    "\n",
    "[原题](https://mp.weixin.qq.com/s/3HwWXIsBH6AzfFCC5fyVDQ)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Question\n",
    "\n",
    "You are given an array of tuples (start, end) representing time intervals for lectures. The intervals may be overlapping. Return the number of rooms that are required.\n",
    "\n",
    "```text\n",
    "Input: [(30, 75), (0, 50), (60, 150)]\n",
    "Output: 2\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def minimun_rooms(schedule: list):\n",
    "    ''' Main Algorithm '''\n",
    "    \n",
    "    # Sort the events with their starting time.\n",
    "    schedule.sort(key=lambda x: x[0])\n",
    "    \n",
    "    # Combine all events to a new schedule.\n",
    "    total = []\n",
    "    \n",
    "    # Check all events in the raw schedule.\n",
    "    for event in schedule:\n",
    "        # Initialize the combination flag.\n",
    "        flag = False\n",
    "        \n",
    "        # Check all rooms if they are available.\n",
    "        for room in total:\n",
    "            # It starts after unavailable time.\n",
    "            if event[0] >= room['end']:\n",
    "                # Arrange it! Refresh the unavailable period.\n",
    "                room['end'] = event[1]\n",
    "                \n",
    "                # Update the flag.\n",
    "                flag = True\n",
    "                break\n",
    "            \n",
    "            # Or it finishes before unavailable time.\n",
    "            elif event[1] <= room['begin']:\n",
    "                room['begin'] = event[0]\n",
    "                flag = True\n",
    "                break\n",
    "        \n",
    "        # If there's no available room for this event,\n",
    "        # Arrange for a new room.\n",
    "        if flag is False:\n",
    "            total.append({'begin': event[0], 'end': event[1]})\n",
    "    \n",
    "    # Return the amount of arranged rooms.\n",
    "    return len(total)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "source": [
    "''' Test Scripts '''\n",
    "print(minimun_rooms([(30, 75), (0, 50), (60, 150), (50, 60), (0, 30)]))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
